//
//  ObtainNViewController.swift
//  AreaChainblock
//
//  Created by 赵佟越 on 2018/9/27.
//  Copyright © 2018年 zhaotongyue. All rights reserved.
//

import UIKit
import SwiftyUserDefaults
import MJRefresh

class ObtainNViewController: BaseViewController ,UITableViewDelegate, UITableViewDataSource,UIGestureRecognizerDelegate,UINavigationControllerDelegate{
    let header = MJRefreshNormalHeader()
    var nNumber : NSString! = ""
    var myuserModel = LogInModel();
    var moneyLabel = UILabel()
    override func viewDidLoad() {
        super.viewDidLoad()
        makeBaseUI()
        getData()
        self.navigationController?.interactivePopGestureRecognizer?.delegate = self
        // Do any additional setup after loading the view.
    }
    @objc func headerRefresh(){
       
        getData()
    }
    func pushViewController(viewController: UIViewController, animated: Bool) {
        super.navigationController?.pushViewController(viewController, animated: animated)
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
       layoutNav()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    //MARK: - Private Methods
    func getData() {
        MyNetwork.request(target: .getTwoWay(user_id: Defaults[.userID]!), success: { (result) in
            kLog(result)
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            self.header.endRefreshing()
            if needModel.code == 1111{
                self.myuserModel.yy_modelSet(withJSON:(result as AnyObject)["data"]);
                self.myTableView.reloadData()
                if self.myuserModel.tg_n != nil{
                    self.moneyLabel.text = String(format: "%@ MT", self.myuserModel.tg_n!)
                }
            }else{
                self.header.endRefreshing(); self.navigationController?.view.makeToast(XALanguageManager.getString(key: "失败"))
            }
            
        }) { (error) in
            //kLog(error.localizedDescription)
            self.header.endRefreshing(); self.navigationController?.view.makeToast(error.localizedDescription)
        }
    }
    
    func layoutNav() {
        //nav
        self.navigationController?.setNavigationBarHidden(true, animated: true) //navigationController?.navigationBar.subviews[0].removeFromSuperview()//去
//
    }
    
    func makeBaseUI(){
        self.view.addSubview(myTableView)
        header.setRefreshingTarget(self, refreshingAction: #selector(ObtainNViewController.headerRefresh))
        myTableView.mj_header = header
        
        let backImageView1 = UIImageView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 240*_kScreenWidth))
        backImageView1.image = UIImage.init(named: "组 4927")
        self.view.addSubview(backImageView1)
        
        let backImageView = UIImageView(frame: CGRect(x: 15, y: 40, width: 20, height: 20))
        backImageView.image = UIImage.init(named: "返回 2035")
        backImageView.isUserInteractionEnabled = true
        self.view.addSubview(backImageView)
        
        let backBtn = UIButton(frame: CGRect(x: 0, y: 10, width: 80, height: 50))
        backBtn.addTarget(self, action: #selector(ObtainNViewController.backAction), for: .touchUpInside)
        self.view.addSubview(backBtn)
        
        
        let navtitleLabel = UILabel()
        self.view.addSubview(navtitleLabel)
        navtitleLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.centerY.equalTo(backImageView)
            make.size.equalTo(CGSize(width: 200, height: 40))
        }
        navtitleLabel.text = XALanguageManager.getString(key: "Obtain N")
        navtitleLabel.textColor = UIColor.white
        navtitleLabel.textAlignment = .center
        navtitleLabel.font = UIFont.boldSystemFont(ofSize: 17)
        
        
        let titleLabel = UILabel()
        self.view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(15)
            make.top.equalTo(backImageView.snp.bottom).offset(30)
            make.size.equalTo(CGSize(width: 200, height: 40))
        }
        titleLabel.text = XALanguageManager.getString(key: "Obtain N")
        titleLabel.textColor = UIColor.white
        titleLabel.textAlignment = .left
        titleLabel.font = UIFont.boldSystemFont(ofSize: 20)
        
        
        
        let titleLabel1 = UILabel()
        self.view.addSubview(titleLabel1)
        titleLabel1.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(15)
            make.top.equalTo(titleLabel.snp.bottom).offset(10)
            make.size.equalTo(CGSize(width: kScreenWidth - 30, height: 15))
        }
        titleLabel1.text = XALanguageManager.getString(key: "The more tasks the task does, the faster N grows.")
        titleLabel1.textColor = UIColor.white
        titleLabel1.textAlignment = .left
        titleLabel1.font = UIFont.systemFont(ofSize: 14)
        
        
        
        self.view.addSubview(moneyLabel)
        moneyLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(15)
            make.top.equalTo(titleLabel1.snp.bottom).offset(30)
            make.size.equalTo(CGSize(width: 200, height: 15))
        }
       
        moneyLabel.textColor = UIColor.white
        moneyLabel.textAlignment = .left
        moneyLabel.font = UIFont.boldSystemFont(ofSize: 20)
        
        let bottomBtn = UIButton(type: .system)
        self.view.addSubview(bottomBtn)
        bottomBtn.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(15)
            make.bottom.equalTo(self.view.snp.bottom).offset(-30)
            make.size.equalTo(CGSize(width: kScreenWidth - 30, height: 44))
        }
        bottomBtn.setTitleColor(UIColor.white, for: .normal)
        bottomBtn.layer.cornerRadius = 22
        bottomBtn.backgroundColor = UIColor("#418DFF")
        bottomBtn.setTitle(XALanguageManager.getString(key: "Invite now"), for: .normal)
        bottomBtn.isHidden = true
//        moneyLabel.text = XALanguageManager.getString(key: "1123N")
//        moneyLabel.textColor = UIColor.white
//        moneyLabel.textAlignment = .left
//        moneyLabel.font = UIFont.boldSystemFont(ofSize: 20)
        bottomBtn.addTarget(self, action: #selector(self.shareAction), for: .touchUpInside)
        
        
    }
    
    @objc func shareAction(){
        var platarr:NSArray=[1,2]
        if UIApplication.shared.canOpenURL(URL.init(string: "sinaweibo://")!) {
            platarr=[1,2]
        }
        UMSocialUIManager.setPreDefinePlatforms(platarr as! [Any])
        
         UMSocialUIManager.showShareMenuViewInWindow { (UMSocialPlatformTypestr, array) in
            print("")
            switch UMSocialPlatformTypestr {
            case UMSocialPlatformType.wechatSession:
                print("微信")
            case UMSocialPlatformType.wechatTimeLine:
                print("微信朋友圈")
            case UMSocialPlatformType.QQ:
                print("QQ")
            case UMSocialPlatformType.qzone:
                print("QQ空间")
            case UMSocialPlatformType.sms:
                print("短信")
            default :
                print("没有")
            }
        self.sharewebPageToPlatformType(UMSocialPlatformTypestr)
        }
        
    }
    func sharewebPageToPlatformType(_ platformType:UMSocialPlatformType)  {
        
        let messageObject=UMSocialMessageObject.init()
        let thumurl="https://mobile.umeng.com/images/pic/home/social/img-1.png"
        let shareObject = UMShareWebpageObject.shareObject(withTitle: "DKE", descr: "欢迎使用DKE", thumImage: thumurl)
        //
        shareObject?.webpageUrl=String(format: "http://renedescartes.io/web/home/share?code=%@", Defaults[.userPhone]!)//;url就是你要分享的网址
        messageObject.shareObject=shareObject
        UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: self) { (data, error) in
            if (error != nil) {
                
                /**
                 *  根据等级打印日志
                 *
                 *  @param flagString  控制打印分级的标志字符串
                 *  @see  below  UMSocialLogClosedFlagString...and so on
                 *  @param file        打印日志的文件
                 *  @param function    打印日志的函数
                 *  @param line        打印的日志的行数
                 *  @param format      需要打印的日志格式内容
                 *  @param ...         可变参数
                 *  @dicuss 本库不需要直接调用，可以用简易函数宏 @see UMSocialLogError,UMSocialLogWarn,UMSocialLogInfo,UMSocialLogDebug
                 */
                // UMSocialLog()
                
                print(String.init(format: "%@", error! as CVarArg))
            }else{
                
                if data is UMSocialShareResponse
                {
                    let resp:UMSocialShareResponse=data as! UMSocialShareResponse
                    print(resp.message)
                }else{
                    print(String.init(format: "%@", data! as! CVarArg))
                }
                
            }
            
        }
        
    }
    
    @objc func backAction(){
        self.navigationController?.popViewController(animated: true)
    }
    //MARK: - tableView Delegate And DataSource
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          var cell:ObtainNTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "cell")as?ObtainNTableViewCell
        if cell == nil {
            cell = ObtainNTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
        }
        if indexPath.row == 0 {
            cell.titleLabel.text = myuserModel.a_nick_name
            cell.rightLabel.text = myuserModel.a_earning
            cell.myimageView.backgroundColor = UIColor("#4A4AF7")
            let url1 : URL!
            if myuserModel.a_avatar == nil{
                url1 = URL( string:String(format: "http://renedescartes.io%@",""))
            }else{
                url1 = URL( string:String(format: "http://renedescartes.io%@",myuserModel.a_avatar! ))
            }
            
            cell.myimageView.sd_setImage(with: url1, placeholderImage: UIImage.init(named: ""), options: [], progress: nil, completed:nil)
//            cell.detailLabel.text = myuserModel.a_earning
        }else if indexPath.row == 1{
            cell.titleLabel.text = myuserModel.b_nick_name  
             cell.rightLabel.text =  myuserModel.b_earning
//            cell.detailLabel.text = myuserModel.b_earning
            
            let url1 : URL!
            if myuserModel.b_avatar == nil{
                url1 = URL( string:String(format: "http://renedescartes.io%@",""))
            }else{
                url1 = URL( string:String(format: "http://renedescartes.io%@",myuserModel.b_avatar! ))
            }
            
            cell.myimageView.sd_setImage(with: url1, placeholderImage: UIImage.init(named: ""), options: [], progress: nil, completed:nil)
            cell.myimageView.backgroundColor = UIColor("#F74A8B")
        }
        
        
        cell?.accessoryType = .disclosureIndicator
       
        //        cell?.contentView.addSubview(SelectControllerViewController().view)
        
        cell?.textLabel?.text = ""
        return cell!
    }
    //footer height
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    // row height
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    // header height
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 40
        }else{
            return CGFloat.leastNormalMagnitude
        }
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let backView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 40))
        backView.backgroundColor = UIColor.clear
        let titleLabel = UILabel(frame: CGRect(x: 15, y: 0, width: kScreenWidth, height: 40))
        backView.addSubview(titleLabel)
        
        titleLabel.text = XALanguageManager.getString(key: "My team")
        titleLabel.textColor = UIColor.white
        return backView
        //        return backView
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return ""
    }
    
    // row num
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    // 组数
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    //点击事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0 {
           let Ateam = MynodeListViewController()
            Ateam.teamType = "A"
            self.navigationController?.pushViewController(Ateam, animated: true)
            tableView.deselectRow(at: indexPath, animated: true)
        }else if indexPath.row == 1{
            let Ateam = MynodeListViewController()
            Ateam.teamType = "B"
            self.navigationController?.pushViewController(Ateam, animated: true)
            tableView.deselectRow(at: indexPath, animated: true)
        }
    
    }
    
    override func willMove(toParentViewController parent: UIViewController?) {
        
    }
    
    // MARK: -Button Action
    @objc func centerAction(sender:UIButton){
        let target = sender.tag
        switch target {
        case 1000:
            print("1000")
        case 1001:
            print("1001")
        case 1002:
            print("1002")
        default:
            print("123")
        }
    }
    
    
    
    
    // MARK: - 懒加载
    private lazy var myTableView:UITableView = {
        let myTableView:UITableView
        if UIDevice.current.isX(){
            myTableView = UITableView(frame: CGRect(x: 0, y:  240*_kScreenWidth, width: kScreenWidth, height: kScreenHeight-240*_kScreenWidth), style: UITableViewStyle.grouped)
        }else{
            myTableView = UITableView(frame: CGRect(x: 0, y:  240*_kScreenWidth, width: kScreenWidth, height: kScreenHeight-240*_kScreenWidth), style: UITableViewStyle.grouped)
        }
        myTableView.backgroundColor = UIColor.clear
        myTableView.delegate = self
        myTableView.separatorStyle = .none
        myTableView.dataSource = self
        myTableView.register(UINib.init(nibName: "ObtainNTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        return myTableView
    }()
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}

